const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

const saveUser = user => {
    wx.setStorage({
        key: 'user',
        data: user
    })
}

const readUser = () => {
    return wx.getStorageSync('user')
}

const saveToken = token => {
    wx.setStorage({
        key: 'token',
        data: token
    })
}

const readToken = () => {
    return wx.getStorageSync('token')
}

const clean = () => {
    wx.clearStorageSync()
}

const abbr = content => {
    if (!!content) {
        return content.replace(/<[^<>]+>|&nbsp;/gi, "").slice(0, 20);
    }
    return ""
}

const fmtHTML = function (content, host) {
    if (!!content) {
        content = content.replace(/<img src="\//g, '<img src="' + host + '/')
        content = content.replace(/<img /g, '<img style="width: 100%; height: auto;" ')
    }
    return content;
}

module.exports = {
    formatTime,
    saveUser,
    readUser,
    saveToken,
    readToken,
    clean,
    abbr,
    fmtHTML
}